/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.crm.workorder.web.WorkOrderAction
   Module Description   :

   Date Created      : 2009/11/20
   Original Author   : andy.chuang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.crm.workorder.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.userdetails.UserDetails;

import tw.idv.cut7man.pageable.TagProperties;

import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.admin.utils.AdminHelper;
import com.yaodian100.core.batch.service.BatchJobService;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.JspUtil;
import com.yaodian100.core.form.entity.Form;
import com.yaodian100.core.menu.entity.Option;
import com.yaodian100.core.sms.service.SmsService;
import com.yaodian100.crm.cs.entity.Answer;
import com.yaodian100.crm.cs.entity.CommonQuestionType;
import com.yaodian100.crm.cs.entity.FromChannel;
import com.yaodian100.crm.cs.entity.Question;
import com.yaodian100.crm.cs.entity.QuestionExtraValue;
import com.yaodian100.crm.cs.entity.QuestionType;
import com.yaodian100.crm.cs.service.CsService;
import com.yaodian100.crm.workorder.entity.TaskGroup;
import com.yaodian100.crm.workorder.entity.TaskGroupUser;
import com.yaodian100.crm.workorder.entity.WorkOrder;
import com.yaodian100.crm.workorder.entity.WorkOrderApprove;
import com.yaodian100.crm.workorder.service.WorkOrderService;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.ServiceOrderService;
import com.yaodian100.ec.product.service.OrderCommentService;

/**
 * @author andy.chuang
 * 
 */
public class WorkOrderAction extends ActionSupport {

	/**
     * 
     */
	private static final long serialVersionUID = -3030425102781340068L;
	@Resource
	private BaseManager baseMgr;
	@Resource
	private WorkOrderService workOrderService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private SmsService smsService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private OrderCommentService orderCommentService;

	private String id;
	private String username;
	private String comment;
	private String responser;
	private String workFlowNodeId;
	private String startDate;
	private String endDate;
	private String orderId;

	// for close Order
	private String workOrderId;
	private String questionType;
	private String answer;
	private String note;
	private String showOnProductPage;

	private String type;

	// for create order
	private String questionId;
	private String shortDesc;
	// message
	private String message;

	private String approveComment;
	private String priority;

	private String fromManage;

	private String class1;
	private String class2;
	private String commonQuestionType;
	private String mustInquire;

	private String returnId;

	private String answerId;
	private String content;
	private String processLog;
	@Resource
	private BatchJobService batchJobService;
	@Resource
	private CsService csService;
	private Integer recordSize = 100;

	@Resource
	private ServiceOrderService serviceOrderService;

	private String compensation;

	/**
	 * @return the recordSize
	 */
	public Integer getRecordSize() {
		return recordSize;
	}

	/**
	 * @param recordSize the recordSize to set
	 */
	public void setRecordSize(Integer recordSize) {
		this.recordSize = recordSize;
	}

	/**
	 * @return the orderId
	 */
	public String getOrderId() {
		return orderId;
	}

	/**
	 * @param orderId the orderId to set
	 */
	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	/**
	 * @return the startDate
	 */
	public String getStartDate() {
		return startDate;
	}

	/**
	 * @param startDate the startDate to set
	 */
	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	/**
	 * @return the endDate
	 */
	public String getEndDate() {
		return endDate;
	}

	/**
	 * @param endDate the endDate to set
	 */
	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	/**
	 * @return the processLog
	 */
	public String getProcessLog() {
		return processLog;
	}

	/**
	 * @param processLog the processLog to set
	 */
	public void setProcessLog(String processLog) {
		this.processLog = processLog;
	}

	/**
	 * @return the content
	 */
	public String getContent() {
		return content;
	}

	/**
	 * @param content the content to set
	 */
	public void setContent(String content) {
		this.content = content;
	}

	/**
	 * @return the answerId
	 */
	public String getAnswerId() {
		return answerId;
	}

	/**
	 * @param answerId the answerId to set
	 */
	public void setAnswerId(String answerId) {
		this.answerId = answerId;
	}

	/**
	 * @return the returnId
	 */
	public String getReturnId() {
		return returnId;
	}

	/**
	 * @param returnId the returnId to set
	 */
	public void setReturnId(String returnId) {
		this.returnId = returnId;
	}

	/**
	 * @return the shortDesc
	 */
	public String getShortDesc() {
		return shortDesc;
	}

	/**
	 * @param shortDesc the shortDesc to set
	 */
	public void setShortDesc(String shortDesc) {
		this.shortDesc = shortDesc;
	}

	/**
	 * @return the class1
	 */
	public String getClass1() {
		return class1;
	}

	/**
	 * @param class1 the class1 to set
	 */
	public void setClass1(String class1) {
		this.class1 = class1;
	}

	/**
	 * @return the class2
	 */
	public String getClass2() {
		return class2;
	}

	/**
	 * @param class2 the class2 to set
	 */
	public void setClass2(String class2) {
		this.class2 = class2;
	}

	/**
	 * @return the commonQuestionType
	 */
	public String getCommonQuestionType() {
		return commonQuestionType;
	}

	/**
	 * @param commonQuestionType the commonQuestionType to set
	 */
	public void setCommonQuestionType(String commonQuestionType) {
		this.commonQuestionType = commonQuestionType;
	}

	/**
	 * @return the mustInquire
	 */
	public String getMustInquire() {
		return mustInquire;
	}

	/**
	 * @param mustInquire the mustInquire to set
	 */
	public void setMustInquire(String mustInquire) {
		this.mustInquire = mustInquire;
	}

	/**
	 * @return the fromManage
	 */
	public String getFromManage() {
		return fromManage;
	}

	/**
	 * @param fromManage the fromManage to set
	 */
	public void setFromManage(String fromManage) {
		this.fromManage = fromManage;
	}

	/**
	 * @return the priority
	 */
	public String getPriority() {
		return priority;
	}

	/**
	 * @param priority the priority to set
	 */
	public void setPriority(String priority) {
		this.priority = priority;
	}

	/**
	 * @return the approveComment
	 */
	public String getApproveComment() {
		return approveComment;
	}

	/**
	 * @param approveComment the approveComment to set
	 */
	public void setApproveComment(String approveComment) {
		this.approveComment = approveComment;
	}

	/**
	 * @return the questionId
	 */
	public String getQuestionId() {
		return questionId;
	}

	/**
	 * @param questionId the questionId to set
	 */
	public void setQuestionId(String questionId) {
		this.questionId = questionId;
	}

	/**
	 * @return the questionType
	 */
	public String getQuestionType() {
		return questionType;
	}

	/**
	 * @param questionType the questionType to set
	 */
	public void setQuestionType(String questionType) {
		this.questionType = questionType;
	}

	/**
	 * @return the answer
	 */
	public String getAnswer() {
		return answer;
	}

	/**
	 * @param answer the answer to set
	 */
	public void setAnswer(String answer) {
		this.answer = answer;
	}

	/**
	 * @return the note
	 */
	public String getNote() {
		return note;
	}

	/**
	 * @param note the note to set
	 */
	public void setNote(String note) {
		this.note = note;
	}

	/**
	 * @return the workOrderId
	 */
	public String getWorkOrderId() {
		return workOrderId;
	}

	/**
	 * @param workOrderId the workOrderId to set
	 */
	public void setWorkOrderId(String workOrderId) {
		this.workOrderId = workOrderId;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * @return the workFlowNodeId
	 */
	public String getWorkFlowNodeId() {
		return workFlowNodeId;
	}

	/**
	 * @param workFlowNodeId the workFlowNodeId to set
	 */
	public void setWorkFlowNodeId(String workFlowNodeId) {
		this.workFlowNodeId = workFlowNodeId;
	}

	/**
	 * @return the responser
	 */
	public String getResponser() {
		return responser;
	}

	/**
	 * @param responser the responser to set
	 */
	public void setResponser(String responser) {
		this.responser = responser;
	}

	/**
	 * @return the comment
	 */
	public String getComment() {
		return comment;
	}

	/**
	 * @param comment the comment to set
	 */
	public void setComment(String comment) {
		this.comment = comment;
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	// dispatch
	private String iamlazy;

	/**
	 * @return the iamlazy
	 */
	public String getIamlazy() {
		return iamlazy;
	}

	/**
	 * @param iamlazy the iamlazy to set
	 */
	public void setIamlazy(String iamlazy) {
		this.iamlazy = iamlazy;
	}

	private String AJAX;

	public String page() {
		if (AJAX != null && AJAX.equals("true")) {
			return iamlazy + "_ajax";
		} else {
			return iamlazy;
		}
	}

	private String returnPage(String orgPage) {
		if (AJAX != null && AJAX.equals("true")) {
			return orgPage + "_ajax";
		} else {
			return orgPage;
		}
	}

	public static void main(String args[]) {
		// System.out.println(WorkOrder.APPROVE_STATUS.APPROVED.value());
	}

	public String get() {
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.parseLong(id));
		UserDetails userDetails = AdminHelper.getUserDetails();
		User user = (User) baseMgr.get(User.class, userDetails.getUsername());
		if (wo.getApproveStatus() == 0) {
			message = "工单审核中，无法取得";
		} else if ((wo.getOwner() == null && user.getGroup().getCode().equals(wo.getResponseGroup()) || (wo.getOwner() == null && wo
				.getResponseGroup() == null))) {
			workOrderService.get(wo.getId(), user.getUsername());
		} else {
			// message = "工單已經被其他人取走";
			// 代结后建新单
			if (wo.getStatus() == 0) {
				WorkOrder nwo = workOrderService.proxyOrder(id, user.getUsername());
				id = String.valueOf(nwo.getId());
			} else {
				message = "工单已在处理中，无法取得";
			}
		}
		return returnPage("get");
	}

	public String assign() {
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.parseLong(id));
		UserDetails userDetails = AdminHelper.getUserDetails();
		User user = (User) baseMgr.get(User.class, userDetails.getUsername());
		Boolean isManager = JspUtil.isManager(user.getUsername());
		if (isManager) {
			if (username.equals("")) {
				wo.setOwner(null);
			} else {
				User theUser = (User) baseMgr.get(User.class, username);
				wo.setOwner(theUser);
			}
			baseMgr.update(wo);
		}
		return returnPage("assign");
	}

	public String forwardOrder() {

		workOrderService.forwardOrder(id, comment, responser, workFlowNodeId, Integer.parseInt(priority), class1, class2,
				commonQuestionType, mustInquire, answer, showOnProductPage);
		return returnPage("forwardOrder");
	}

	public String backwardOrder() {

		workOrderService.backwardOrder(id, comment, responser, workFlowNodeId, Integer.parseInt(priority), class1, class2,
				commonQuestionType, mustInquire, answer, showOnProductPage);
		return returnPage("backwardOrder");
	}

	public String approveOrder() {
		if (id != null && id.length() > 0) {
			message = workOrderService.approveOrder(id, approveComment);
		}
		return returnPage("approveOrder");
	}

	public String rejectOrder() {
		if (id != null && id.length() > 0) {
			workOrderService.rejectOrder(id, approveComment);
		}
		return returnPage("rejectOrder");
	}

	public String assignFromMyWorkOrder() {
		assign();
		return returnPage("assignFromMyWorkOrder");
	}

	public String closeOrder() {
		workOrderService.closeOrder(id, answer, showOnProductPage, workOrderId, note, WorkOrder.FINISH_TYPE.SELF.value(),
				priority, class1, class2, commonQuestionType, compensation);
		if (fromManage != null && fromManage.equals("true")) {
			return returnPage("list");
		}
		return returnPage("closeOrder");
	}

	public String cancelOrderAndCloseWo() {
		workOrderService.closeOrder(id, answer, showOnProductPage, workOrderId, note, WorkOrder.FINISH_TYPE.SELF.value(),
				priority, class1, class2, commonQuestionType, compensation);
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(workOrderId));
		Object[] qevs = baseMgr.queryByHql("from QuestionExtraValue where question.id=? and attribute.name=?",
				new Object[] { wo.getDomainId(), "orderId" });
		QuestionExtraValue qev = (QuestionExtraValue) qevs[0];
		String orderId = qev.getValue();
		Orders order = (Orders) baseMgr.get(Orders.class, orderId);
		qevs = baseMgr.queryByHql("from QuestionExtraValue where question.id=? and attribute.name=?", new Object[] {
				wo.getDomainId(), "cancelReason" });
		qev = (QuestionExtraValue) qevs[0];
		String cancelReason = qev.getValue();

		if (null == order) {
			message = " 此订单编号不存在，无法取消";
		} else if (!"25".equals(order.getOrderSt())) {
			message = " 此订单的状态已非出货处理中，无法取消";
		} else {
			workOrderService.closeOrder(id, answer, showOnProductPage, workOrderId, note, WorkOrder.FINISH_TYPE.SELF.value(),
					null, null, null, null, compensation);
			batchJobService.save("ShippingExceptionCancelOrder", "<root><orderId>" + orderId + "</orderId><cancelType>"
					+ cancelReason + "</cancelType></root>", null, orderId);

			message = "，并已取消订单";

			// int stockNum = jdbcTemplate.queryForInt("select count(*) from EC_SPEC_INVENTORY_VALID where VALID_ID = '" +
			// orderId
			// + "outStock" + "'");
			// if (stockNum == 0) {
			// StringBuffer sql = new StringBuffer("insert into EC_SPEC_INVENTORY_VALID (VALID_ID) values (?) ");
			// jdbcTemplate.update(sql.toString(), new Object[] { orderId + "outStock" });
			List<OrderProduct> products = order.getOrderProduct();
			StringBuffer productIds = new StringBuffer();
			for (OrderProduct product : products) {
				productIds.append(product.getProdId()).append(",");
			}
			if (productIds.length() > 0) {
				productIds.deleteCharAt(productIds.length() - 1);
			}
			this.csService.sendOutOfStockCancelOrder(wo, orderId, productIds.toString());
			// }

		}

		return returnPage("cancelOrderAndCloseWo");
	}

	/**
	 * 商品評論審核
	 * 
	 * @return
	 */
	public String closeProductComment() throws NumberFormatException, Exception {
		workOrderService.closeProductCommentOrder(id, answer, showOnProductPage, workOrderId, note,
				WorkOrder.FINISH_TYPE.SELF.value(), priority, class1, class2, commonQuestionType, compensation, type);
		return returnPage("approveProductCommentCloseWo");
	}

	/**
	 * 验证手机
	 * 
	 * @return
	 */
	public String activateMobileCloseWo() {
		workOrderService.closeOrder(id, answer, showOnProductPage, workOrderId, note, WorkOrder.FINISH_TYPE.SELF.value(),
				priority, class1, class2, commonQuestionType, compensation);
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(workOrderId));

		Member member = memberService.get(wo.getQuestion().getMemberId());
		if (null == member) {
			message = "  查无此会员";
			return returnPage("activateMobileCloseWo");
		}
		if (StringUtils.isBlank(member.getTempMobile())) {
			message = "  会员无待验证手机号 或 会员已验证成功";
			return returnPage("activateMobileCloseWo");
		}
		if ((null == member.getActiveDate()) && (!"nonmember".equals(member.getApplySource()))) {// 尚未激活会员
			Member t = memberService.setMobileMemberActive(member.getLoginId(), member.getActivateMobileToken());

			if (null == t) {
				message = "  验证失败";
			}
		} else {
			if (null == memberService.setModifyMobileActive(member)) {
				message = "  验证失败，手机号码：" + member.getTempMobile() + " 已被使用。";
			}
		}
		return returnPage("activateMobileCloseWo");
	}

	/**
	 * 物流异常工单 - 结单并进行退款
	 * 
	 * @return
	 */
	public String cancelFailDeliverOrderAndCloseWo() {
		workOrderService.closeOrder(id, answer, showOnProductPage, workOrderId, note, WorkOrder.FINISH_TYPE.SELF.value(),
				priority, class1, class2, commonQuestionType, compensation);
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(workOrderId));
		Map<String, QuestionExtraValue> qev = wo.getQuestion().getExtraValue();
		String orderId = qev.get("orderId").getValue();
		String soId = qev.get("soId").getValue();
		String cancelReason = "53";
		String batchContent = "<root><orderId>" + orderId + "</orderId><cancelType>" + cancelReason + "</cancelType>";
		if (StringUtils.isNotBlank(soId)) {
			batchContent += ("<serviceOrderId>" + soId + "</serviceOrderId>");
		}
		batchContent += "</root>";
		batchJobService.save("DeliveryDelayCancelSalesOrder", batchContent);
		return returnPage("cancelFailDeliverOrderAndCloseWo");
	}

	public String partialCancelOrderAndCloseWo() {
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(workOrderId));
		Object[] qevs = baseMgr.queryByHql("from QuestionExtraValue where question.id=? and attribute.name=?",
				new Object[] { wo.getDomainId(), "orderId" });
		QuestionExtraValue qev = (QuestionExtraValue) qevs[0];
		String orderId = qev.getValue();
		qevs = baseMgr.queryByHql("from QuestionExtraValue where question.id=? and attribute.name=?", new Object[] {
				wo.getDomainId(), "cancelReason" });
		qev = (QuestionExtraValue) qevs[0];
		/*
		 * String cancelReason = qev.getValue();
		 * 
		 * 
		 * if (!StringUtils.isBlank(orderId)) { batchJobService.save("ShippingExceptionCancelOrder", "<root><orderId>" +
		 * orderId + "</orderId><cancelType>" + cancelReason + "</cancelType></root>"); }
		 */
		// 建立部份取消单
		qevs = baseMgr.queryByHql("from QuestionExtraValue where question.id=? and attribute.name=?", new Object[] {
				wo.getDomainId(), "productId" });
		qev = (QuestionExtraValue) qevs[0];
		String productId = qev.getValue();
		DetachedCriteria dc = DetachedCriteria.forClass(FromChannel.class);
		dc.add(Restrictions.eq("title", "内部人员"));
		Object[] channels = baseMgr.findByCriteria(dc);
		WorkOrder pco = csService.createPartialCancelOrder(orderId, productId, note, (FromChannel) channels[0]);
		message = "，并已生成部份取消工单";
		// pco.setResponseGroup(wo.getOwner().getGroupName());
		// pco.setOwner(wo.getOwner());
		pco.setResponseGroup("A-30-400-000");
		baseMgr.update(pco);

		workOrderService.closeOrder(id, answer, showOnProductPage, workOrderId, note, WorkOrder.FINISH_TYPE.SELF.value(),
				priority, class1, class2, commonQuestionType, compensation);

		return returnPage("partialCancelOrderAndCloseWo");
	}

	/**
	 * @return the showOnProductPage
	 */
	public String getShowOnProductPage() {
		return showOnProductPage;
	}

	/**
	 * @param showOnProductPage the showOnProductPage to set
	 */
	public void setShowOnProductPage(String showOnProductPage) {
		this.showOnProductPage = showOnProductPage;
	}

	/**
	 * @return the aJAX
	 */
	public String getAJAX() {
		return AJAX;
	}

	/**
	 * @param aJAX the aJAX to set
	 */
	public void setAJAX(String aJAX) {
		AJAX = aJAX;
	}

	public String confirmReturnProductApply() {
		workOrderService.confirmReturnProductApply(id, answer, showOnProductPage, workOrderId, note, returnId);
		return returnPage("confirmReturnProductApply");
	}

	public String cancelReturnProductApply() {
		workOrderService.cancelReturnProductApply(id, answer, showOnProductPage, workOrderId, note, returnId);
		return returnPage("cancelReturnProductApply");
	}

	public String updateAnswer() {
		WorkOrder workOrder = (WorkOrder) baseMgr.get(WorkOrder.class, Long.parseLong(workOrderId));
		workOrder.setApproveStatus(WorkOrder.APPROVE_STATUS.INIT.value());
		baseMgr.update(workOrder);
		Answer answer = (Answer) baseMgr.get(Answer.class, answerId);
		answer.setContent(content);
		baseMgr.update(answer);
		return returnPage("updateAnswer");
	}

	private WorkOrder workOrder;

	/**
	 * @return the workOrder
	 */
	public WorkOrder getWorkOrder() {
		return workOrder;
	}

	/**
	 * @param workOrder the workOrder to set
	 */
	public void setWorkOrder(WorkOrder workOrder) {
		this.workOrder = workOrder;
	}

	private TagProperties tp;
	private Object[] workOrders;

	/**
	 * @return the workOrders
	 */
	public Object[] getWorkOrders() {
		return workOrders;
	}

	/**
	 * @param workOrders the workOrders to set
	 */
	public void setWorkOrders(Object[] workOrders) {
		this.workOrders = workOrders;
	}

	/**
	 * @return the tp
	 */
	public TagProperties getTp() {
		return tp;
	}

	/**
	 * @param tp the tp to set
	 */
	public void setTp(TagProperties tp) {
		this.tp = tp;
	}

	public String updateProcessLog() {
		WorkOrder workOrder = (WorkOrder) baseMgr.get(WorkOrder.class, Long.parseLong(workOrderId));
		if (workOrder.getStatus() == WorkOrder.STATUS.INIT.value()
				|| workOrder.getStatus() == WorkOrder.STATUS.RETURNED.value()) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String updateLog = "(" + AdminHelper.getUser().getUsername() + "/" + sdf.format(new Date()) + ")";
			// 只有在初始及已返回狀態可以更新process log
			if (workOrder.getProcessLog() != null) {
				workOrder.setProcessLog(workOrder.getProcessLog() + "\r\n" + processLog);
			} else {
				workOrder.setProcessLog(processLog);
			}
			workOrder.setProcessLog(workOrder.getProcessLog() + updateLog);
			baseMgr.update(workOrder);
			this.workOrder = workOrder;
		}
		return returnPage("updateProcessLog");
	}

	private String notStatus;

	/**
	 * @return the notStatus
	 */
	public String getNotStatus() {
		return notStatus;
	}

	/**
	 * @param notStatus the notStatus to set
	 */
	public void setNotStatus(String notStatus) {
		this.notStatus = notStatus;
	}

	private void searchWO() {
		User user = AdminHelper.getUser();
		JspUtil.criteriaForName(WorkOrder.class.getName());

		Boolean isCSRManager = false;

		Object[] taskGroups = baseMgr.queryByHql("from TaskGroupUser where user.username=?", new Object[] { user
				.getUsername() });
		for (int i = 0; i < taskGroups.length; i++) {
			TaskGroupUser tga = (TaskGroupUser) taskGroups[i];
			if (tga.getTaskGroup().getId().substring(0, 1).equals("C")) {
				if (tga.getTaskRole().equals(TaskGroup.GROUP_ROLE.MANAGER.getValue())) {
					isCSRManager = true;
				}
			}

		}
		String hqlManagerGroupIds = "select taskGroup.id from TaskGroupUser where user.username=? and taskRole=?";
		Object[] managerGroupIds = baseMgr.customHqlQuery(hqlManagerGroupIds, new Object[] { user.getUsername(),
				TaskGroup.GROUP_ROLE.MANAGER.getValue() });
		String managerGroupIdsStr = "";
		for (int i = 0; i < managerGroupIds.length; i++) {
			if (!managerGroupIdsStr.equals("")) {
				managerGroupIdsStr += ",";
			}
			managerGroupIdsStr += "'" + managerGroupIds[i] + "'";
		}
		if (managerGroupIdsStr.equals("")) {
			managerGroupIdsStr = "'NA--'";
		}
		// response groups
		String hqlResponseGroupIds = "select taskGroup.id from TaskGroupUser where user.username=? and (taskRole=? or taskRole=? or taskRole=?)";
		Object[] responseGroupIds = baseMgr.customHqlQuery(hqlResponseGroupIds, new Object[] { user.getUsername(),
				TaskGroup.GROUP_ROLE.MANAGER.getValue(), TaskGroup.GROUP_ROLE.OBSERVER.getValue(),
				TaskGroup.GROUP_ROLE.MEMBER.getValue() });
		String responseGroupIdsStr = "";
		for (int i = 0; i < responseGroupIds.length; i++) {
			if (!responseGroupIdsStr.equals("")) {
				responseGroupIdsStr += ",";
			}
			responseGroupIdsStr += "'" + responseGroupIds[i] + "'";
		}
		if (responseGroupIdsStr.equals("")) {
			responseGroupIdsStr = "'NA--'";
		}

		// approve groups
		// String hqlApproveGroupIds =
		// "select taskGroup.id from TaskGroupUser where user.username=? and (taskRole=? or taskRole=?) ";
		// Object[] approveGroupIds = baseMgr.customHqlQuery(hqlApproveGroupIds, new Object[] { user.getUsername(),
		// TaskGroup.GROUP_ROLE.MANAGER.getValue(), TaskGroup.GROUP_ROLE.MEMBER.getValue() });
		// String approveGroupIdsStr = "";
		// for (int i = 0; i < approveGroupIds.length; i++) {
		// if (!responseGroupIdsStr.equals("")) {
		// approveGroupIdsStr += ",";
		// }
		// approveGroupIdsStr = "'" + approveGroupIds[i] + "'";
		// }
		// if (responseGroupIdsStr.equals("")) {
		// approveGroupIdsStr = "'NA--'";
		// }

		if (isCSRManager) {
			// 客服工单
			String hqlUsernames = "select user.user.username from TaskGroupUser user where user.taskGroup.id like ?";
			Object[] usernames = baseMgr.customHqlQuery(hqlUsernames, new Object[] { "C%" });

			String userNames = "'SYSTEM'";
			for (int i = 0; i < usernames.length; i++) {
				userNames += ",'" + usernames[i] + "'";
			}

			JspUtil.initHql("from WorkOrder w ");
			JspUtil
					.compositeHql(
							"((w.node is null and w.modifyUser in("
									+ userNames
									+ ") or w.createUser in("
									+ userNames
									+ ")) or (w.node is not null and ((w.responseGroup like ? or w.responseGroup in(:responseGroup)) and w.approveStatus=?)))",
							new Object[] { "C%", 1 }, "and");

		} else {
			// 非客服
			JspUtil.initHql("from WorkOrder w");
			JspUtil.compositeHql("((((w.responseGroup in (:responseGroup) and w.approveStatus=?))))", new Object[] { 1 },
					"and");

		}

		JspUtil.compositeHql("w.owner.username=?", new Object[] { responser }, "and");
		if (startDate != null && startDate.length() > 0) {
			startDate += " 00:00";
			JspUtil.compositeHql("w.createDate>=?", new Object[] { JspUtil.toDate(startDate, "yyyy-MM-dd HH:mm") }, "and");
		}
		if (endDate != null && endDate.length() > 0) {
			endDate += " 23:59";
			JspUtil.compositeHql("w.createDate<=?", new Object[] { JspUtil.toDate(endDate, "yyyy-MM-dd HH:mm") }, "and");
		}
		JspUtil.compositeHql("w.question.extraValue['orderId'].value=?", new Object[] { orderId }, "and");
		JspUtil.compositeHql("w.question.memberId=?", new Object[] { memberId }, "and");
		JspUtil.compositeHql("w.priority=?", new Object[] { priority }, "and");

		if (status != null && status.equals("initNotget")) {
			JspUtil.compositeHql(
					"w.status=? and w.approveStatus=? and  (w.responseGroup=? or w.responseGroup is null) and w.owner is null",
					new Object[] { 0, 1, user.getGroup().getCode() }, "and");
		} else {
			JspUtil.compositeHql("w.status=?", new Object[] { status }, "and");
		}
		JspUtil.compositeHql("w.domainId=?", new Object[] { domainId }, "and");
		JspUtil.compositeHql("w.approveStatus=?", new Object[] { approveStatus }, "and");
		if (questionType != null && questionType.equals("CommonQuestion_product")) {
			JspUtil.compositeHql("w.question.type=? and w.question.extraValue['isProductQAA'].value=?", new Object[] {
					"CommonQuestion", "true" }, "and");
		} else if (questionType != null && questionType.equals("CommonQuestion")) {
			JspUtil.compositeHql("w.question.type=? and w.question.extraValue['isProductQAA'].value!=?", new Object[] {
					"CommonQuestion", "true" }, "and");

		} else {
			JspUtil.compositeHql("w.question.type=?", new Object[] { questionType }, "and");
		}
		JspUtil.compositeHql("w.id=?", new Object[] { workOrderId }, "and");
		JspUtil.compositeHql("w.createGroup=?", new Object[] { taskGroupId }, "and");
		JspUtil.compositeHql("w.createUser=?", new Object[] { createUser }, "and");
		JspUtil.compositeHql("w.responseGroup=?", new Object[] { myTaskGroupId }, "and");
		JspUtil.compositeHql("w.owner.username=?", new Object[] { responser }, "and");
		JspUtil.compositeHql("w.question.extraValue['class1'].value=?", new Object[] { class1 }, "and");
		JspUtil.compositeHql("w.question.extraValue['class2'].value=?", new Object[] { class2 }, "and");
		JspUtil.compositeHql("w.question.extraValue['commonQuestionType'].value=?", new Object[] { commonQuestionType },
				"and");
		JspUtil.compositeHql("w.question.deliver=?", new Object[] { deliver }, "and");
		if (notStatus != null && notStatus.length() > 0) {
			JspUtil.compositeHql("w.status!=?", new Object[] { notStatus }, "and");
		}
		Map<String, Object> hqlValues = JspUtil.compositeHql("w.question.category=?", new Object[] { categoryId }, "and");
		String hql = (String) hqlValues.get("hql");
		hql = JspUtil.replaceAll(hql, ":responseGroup", managerGroupIdsStr);
		List<Object> values = (List<Object>) hqlValues.get("values");
		hql += " order by w.status asc, w.domainId desc, w.responseGroup desc, w.approveStatus desc, w.owner desc, w.createDate desc";

		tp = JspUtil.pageableTag("tp", recordSize, 10);
		Object[] arrayValues = null;
		if (values != null) {
			arrayValues = values.toArray();
		}
		workOrders = JspUtil.queryByHql(hql, arrayValues, tp);
	}

	public String index() {
		recordSize = 20;
		searchWO();
		return "list";
	}

	public String toBatchAssign() {
		searchWO();

		return "toBatchAssign";
	}

	public String batchAssign() {
		if (assignType.equals("taskGroup1")) {
			workOrderService.batchAssign(workOrderIds, taskGroup1, responser1, null);
		} else if (assignType.equals("taskGroup2")) {
			int count = workOrderIds.length;
			int avg = (count / responser2.length);
			int lastOwnerCount = count - (responser2.length - 1 * avg);
			assignCounts = new String[responser2.length];
			for (int i = 0; i < responser2.length; i++) {
				assignCounts[i] = String.valueOf(avg);
			}
			assignCounts[assignCounts.length - 1] = String.valueOf(lastOwnerCount);
			workOrderService.batchAssign(workOrderIds, taskGroup2, responser2, assignCounts);
		} else {
			workOrderService.batchAssign(workOrderIds, taskGroup3, responser3, assignCounts);
		}
		message = "已完成派件";
		return "batchAssign";
	}

	public String downloadCsv() {
		JspUtil.criteriaForName(WorkOrder.class.getName());
		Long[] woIds = new Long[workOrderIds.length];
		for (int i = 0; i < workOrderIds.length; i++) {
			woIds[i] = Long.valueOf(workOrderIds[i]);
		}
		JspUtil.criteriaAdd(Restrictions.in("id", woIds));
		Object[] wos = JspUtil.criteriaResult(null);
		file = "workOrderList.csv";
		content = buildCsv(wos);
		return "downloadCsv";
	}

	private String file;

	/**
	 * @return the file
	 */
	public String getFile() {
		return file;
	}

	/**
	 * @param file the file to set
	 */
	public void setFile(String file) {
		this.file = file;
	}

	private String buildCsv(Object[] wos) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		StringBuffer sb = new StringBuffer();

		sb
				.append("问题单编号,工单编号,前单编号,订单编号,会员编号,问题单状态,问题单建立日期,回覆内容,问题大,问题中,问题小,前单说明,问题类型,处理等级,工单状态,工单建立人,工单建立群组,建立时间,处理人,处理群组,处理时间,转单回覆时间,审核状态,审核人,审核群组,审核时间,是否逾期,结案KPI小时,KPI小时\r\n");
		for (Object obj : wos) {
			WorkOrder wo = (WorkOrder) obj;
			// 问题单编号
			sb.append(wo.getDomainId());
			sb.append(",");
			// 工单编号
			sb.append(String.valueOf(wo.getId()));
			sb.append(",");
			// 前单编号
			if (wo.getParent() != null) {
				sb.append(String.valueOf(wo.getParent().getId()));
			}
			sb.append(",");
			// 订单编号
			if (wo.getQuestion().getExtraValue().get("orderId") != null) {
				sb.append(wo.getQuestion().getExtraValue().get("orderId").getValue());
			}
			sb.append(",");
			// 会员编号
			if (wo.getQuestion().getMemberId() != null) {
				sb.append(wo.getQuestion().getMemberId());
			}
			sb.append(",");
			// 问题单状态
			Integer questionStatus = wo.getQuestion().getStatus();
			Option op = JspUtil.menuOption("Question.status", String.valueOf(questionStatus));
			sb.append(op.getName());
			sb.append(",");
			// 问题单建立日期
			sb.append(sdf.format(wo.getQuestion().getCreateDate()));
			sb.append(",");
			// 回覆内容
			String note = wo.getNote();
			if (note != null && note.length() > 0) {
				note = note.replaceAll("\"", "\"\"");
			}
			if (note != null) {
				sb.append("\"" + note + "\"");
			}
			sb.append(",");
			// 问题大
			if (wo.getQuestion().getType().getName().equals("CommonQuestion")) {
				QuestionExtraValue ev = wo.getQuestion().getExtraValue().get("class1");
				if (ev != null && ev.getValue() != null) {
					CommonQuestionType cqt = (CommonQuestionType) baseMgr.get(CommonQuestionType.class, ev.getValue());
					sb.append(cqt.getName());
				}
			}
			sb.append(",");
			// 问题中
			if (wo.getQuestion().getType().getName().equals("CommonQuestion")) {
				QuestionExtraValue ev = wo.getQuestion().getExtraValue().get("class2");
				if (ev != null && ev.getValue() != null) {
					CommonQuestionType cqt = (CommonQuestionType) baseMgr.get(CommonQuestionType.class, ev.getValue());
					sb.append(cqt.getName());
				}
			}
			// 问题小
			sb.append(",");
			if (wo.getQuestion().getType().getName().equals("CommonQuestion")) {
				QuestionExtraValue ev = wo.getQuestion().getExtraValue().get("commonQuestionType");
				if (ev != null && ev.getValue() != null) {
					CommonQuestionType cqt = (CommonQuestionType) baseMgr.get(CommonQuestionType.class, ev.getValue());
					sb.append(cqt.getName());
				}
			}
			sb.append(",");
			// 前单说明
			String comment = "";
			if (wo.getComment() != null) {
				comment = wo.getComment().replaceAll("\"", "\"\"");
			}
			sb.append("\"" + comment + "\"");
			sb.append(",");
			// 问题类型
			String questionType = "";
			if (wo.getQuestion().getType().getName().equals("CommonQuestion")) {
				if (wo.getQuestion().getExtraValue().get("isProductQAA") != null
						&& "true".equals(wo.getQuestion().getExtraValue().get("isProductQAA").getValue())) {
					questionType = "商品问答";
				} else {
					questionType = "客服问答";
				}
			} else {
				questionType = wo.getQuestion().getType().getDescription();
			}
			sb.append(questionType);
			sb.append(",");
			// 处理等级
			String priority = "";
			if (wo.getPriority() == null) {

			} else if (wo.getPriority() == 0) {
				priority = "函件";
			} else if (wo.getPriority() == 1) {
				priority = "一般件";
			} else if (wo.getPriority() == 2) {
				priority = "急件";

			} else if (wo.getPriority() == 3) {
				priority = "特急件";
			}
			sb.append(priority);
			sb.append(",");
			// 工单状态
			sb.append(JspUtil.menuOption("WorkOrder.status", String.valueOf(wo.getStatus())).getName());
			sb.append(",");
			// 工单建立人
			sb.append(wo.getCreateUser());
			sb.append(",");
			// 工单建立群组
			Object[] taskGroupUsers = baseMgr.queryByHql("from TaskGroupUser where user.username=?", new Object[] { wo
					.getCreateUser() });
			if (taskGroupUsers != null && taskGroupUsers.length > 0) {
				TaskGroupUser tgu = (TaskGroupUser) taskGroupUsers[0];
				sb.append(tgu.getTaskGroup().getName() + "(" + tgu.getTaskGroup().getId() + ")");
			}
			sb.append(",");
			// 工单建立时间
			sb.append(sdf.format(wo.getCreateDate()));
			sb.append(",");
			// 处理人
			if (wo.getOwner() != null) {
				sb.append(wo.getOwner().getUsername());
			}
			sb.append(",");
			// 处理群组
			if (wo.getResponseGroup() != null) {
				TaskGroup tg = (TaskGroup) baseMgr.get(TaskGroup.class, wo.getResponseGroup());
				sb.append(tg.getName() + "(" + wo.getResponseGroup() + ")");
			}
			sb.append(",");
			// 处理时间
			if (wo.getStartTime() != null) {
				sb.append(sdf.format(wo.getStartTime()));
			}
			sb.append(",");
			// 转单回覆时间
			String reply = "";
			Object[] parentWos = baseMgr.queryByHql("from WorkOrder where parent.id=?", new Object[] { wo.getId() });
			if (parentWos == null || parentWos.length == 0) {
				reply = "未转单";
			} else {
				WorkOrder parentWo = (WorkOrder) parentWos[0];
				if (parentWo.getFinishTime() != null) {
					reply = sdf.format(parentWo.getFinishTime());
				} else {
					reply = "尚未回覆";
				}
			}
			sb.append(reply);
			sb.append(",");
			// 审核状态
			String approveStatus = "";
			if (wo.getApproveStatus() == 0) {
				approveStatus = "待审核";
			} else if (wo.getApproveStatus() == 1) {
				approveStatus = "已核可";
			} else {
				approveStatus = "已注销";
			}
			sb.append(approveStatus);
			sb.append(",");
			// 审核人
			if (wo.getApprover() != null) {
				sb.append(wo.getApprover());
			}
			sb.append(",");
			// 审核群组
			if (wo.getApproveGroup() != null) {

				TaskGroup tg = (TaskGroup) baseMgr.get(TaskGroup.class, wo.getApproveGroup());
				sb.append(tg.getName() + "(" + wo.getApproveGroup() + ")");
			}
			sb.append(",");
			// 审核时间
			if (wo.getApproveTime() != null) {
				sb.append(sdf.format(wo.getApproveTime()));
			}
			sb.append(",");
			// 是否逾期
			if (wo.getStatus() == 2) {
				if (wo.getPriority() == null || wo.getPriority() == (WorkOrder.PRIORITY.LETTERS.code())) {
					if (wo.getStartTime() != null && wo.getFinishTime() != null) {
						if (JspUtil.subDateInHour(wo.getFinishTime(), wo.getStartTime()) > WorkOrder.PRIORITY.LETTERS.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}
					} else {
						sb.append("否");
					}
				} else if (wo.getPriority() == (WorkOrder.PRIORITY.NORMAL.code())) {
					if (wo.getStartTime() != null && wo.getFinishTime() != null) {
						if (JspUtil.subDateInHour(wo.getFinishTime(), wo.getStartTime()) > WorkOrder.PRIORITY.NORMAL.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}
					} else {
						sb.append("否");
					}
				} else if (wo.getPriority() == (WorkOrder.PRIORITY.HURRY.code())) {
					if (wo.getStartTime() != null && wo.getFinishTime() != null) {
						if (JspUtil.subDateInHour(wo.getFinishTime(), wo.getStartTime()) > WorkOrder.PRIORITY.HURRY.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}
					} else {
						sb.append("否");
					}
				} else if (wo.getPriority() == (WorkOrder.PRIORITY.EMERGENCY.code())) {
					if (wo.getStartTime() != null && wo.getFinishTime() != null) {
						if (JspUtil.subDateInHour(wo.getFinishTime(), wo.getStartTime()) > WorkOrder.PRIORITY.EMERGENCY.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}
					} else {
						sb.append("否");
					}
				}
			} else {
				if (wo.getStartTime() != null) {
					Date currentDate = new Date();
					if (wo.getPriority() == null || wo.getPriority() == (WorkOrder.PRIORITY.LETTERS.code())) {

						if (JspUtil.subDateInHour(currentDate, wo.getStartTime()) > WorkOrder.PRIORITY.LETTERS.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}

					} else if (wo.getPriority() == (WorkOrder.PRIORITY.NORMAL.code())) {
						if (JspUtil.subDateInHour(currentDate, wo.getStartTime()) > WorkOrder.PRIORITY.NORMAL.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}

					} else if (wo.getPriority() == (WorkOrder.PRIORITY.HURRY.code())) {
						if (JspUtil.subDateInHour(currentDate, wo.getStartTime()) > WorkOrder.PRIORITY.HURRY.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}

					} else if (wo.getPriority() == (WorkOrder.PRIORITY.EMERGENCY.code())) {
						if (JspUtil.subDateInHour(currentDate, wo.getStartTime()) > WorkOrder.PRIORITY.EMERGENCY.hours()) {
							sb.append("是");
						} else {
							sb.append("否");
						}

					}
				} else {
					sb.append("否");
				}
			}
			sb.append(",");
			// 结案KPI小时
			if (wo.getStartTime() != null && wo.getFinishTime() != null) {
				sb.append(JspUtil.subDateInHour(wo.getFinishTime(), wo.getStartTime()));
			}
			sb.append(",");
			// KPI小时
			if (wo.getPriority() == null || wo.getPriority() == (WorkOrder.PRIORITY.LETTERS.code())) {
				sb.append(WorkOrder.PRIORITY.LETTERS.hours());
			} else if (wo.getPriority() == (WorkOrder.PRIORITY.NORMAL.code())) {
				sb.append(WorkOrder.PRIORITY.NORMAL.hours());
			} else if (wo.getPriority() == (WorkOrder.PRIORITY.HURRY.code())) {
				sb.append(WorkOrder.PRIORITY.HURRY.hours());
			} else if (wo.getPriority() == (WorkOrder.PRIORITY.EMERGENCY.code())) {
				sb.append(WorkOrder.PRIORITY.EMERGENCY.hours());
			}

			sb.append("\r\n");
		}
		return sb.toString();
	}

	private String taskGroup1, taskGroup2, taskGroup3;
	private String[] responser1, responser2, responser3;
	private String assignType;
	private String[] workOrderIds, assignCounts;

	/**
	 * @return the assignCounts
	 */
	public String[] getAssignCounts() {
		return assignCounts;
	}

	/**
	 * @param assignCounts the assignCounts to set
	 */
	public void setAssignCounts(String[] assignCounts) {
		this.assignCounts = assignCounts;
	}

	/**
	 * @return the workOrderIds
	 */
	public String[] getWorkOrderIds() {
		return workOrderIds;
	}

	/**
	 * @param workOrderIds the workOrderIds to set
	 */
	public void setWorkOrderIds(String[] workOrderIds) {
		this.workOrderIds = workOrderIds;
	}

	/**
	 * @return the assignType
	 */
	public String getAssignType() {
		return assignType;
	}

	/**
	 * @param assignType the assignType to set
	 */
	public void setAssignType(String assignType) {
		this.assignType = assignType;
	}

	/**
	 * @return the taskGroup1
	 */
	public String getTaskGroup1() {
		return taskGroup1;
	}

	/**
	 * @param taskGroup1 the taskGroup1 to set
	 */
	public void setTaskGroup1(String taskGroup1) {
		this.taskGroup1 = taskGroup1;
	}

	/**
	 * @return the taskGroup2
	 */
	public String getTaskGroup2() {
		return taskGroup2;
	}

	/**
	 * @param taskGroup2 the taskGroup2 to set
	 */
	public void setTaskGroup2(String taskGroup2) {
		this.taskGroup2 = taskGroup2;
	}

	/**
	 * @return the taskGroup3
	 */
	public String getTaskGroup3() {
		return taskGroup3;
	}

	/**
	 * @param taskGroup3 the taskGroup3 to set
	 */
	public void setTaskGroup3(String taskGroup3) {
		this.taskGroup3 = taskGroup3;
	}

	/**
	 * @return the responser1
	 */
	public String[] getResponser1() {
		return responser1;
	}

	/**
	 * @param responser1 the responser1 to set
	 */
	public void setResponser1(String[] responser1) {
		this.responser1 = responser1;
	}

	/**
	 * @return the responser2
	 */
	public String[] getResponser2() {
		return responser2;
	}

	/**
	 * @param responser2 the responser2 to set
	 */
	public void setResponser2(String[] responser2) {
		this.responser2 = responser2;
	}

	/**
	 * @return the responser3
	 */
	public String[] getResponser3() {
		return responser3;
	}

	/**
	 * @param responser3 the responser3 to set
	 */
	public void setResponser3(String[] responser3) {
		this.responser3 = responser3;
	}

	private String memberId;
	private String status;
	private String domainId;
	private String approveStatus;
	private String taskGroupId;
	private String createUser;
	private String myTaskGroupId;
	private String deliver;
	private String categoryId;

	/**
	 * @return the memberId
	 */
	public String getMemberId() {
		return memberId;
	}

	/**
	 * @param memberId the memberId to set
	 */
	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	/**
	 * @return the status
	 */
	public String getStatus() {
		return status;
	}

	/**
	 * @param status the status to set
	 */
	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 * @return the domainId
	 */
	public String getDomainId() {
		return domainId;
	}

	/**
	 * @param domainId the domainId to set
	 */
	public void setDomainId(String domainId) {
		this.domainId = domainId;
	}

	/**
	 * @return the approveStatus
	 */
	public String getApproveStatus() {
		return approveStatus;
	}

	/**
	 * @param approveStatus the approveStatus to set
	 */
	public void setApproveStatus(String approveStatus) {
		this.approveStatus = approveStatus;
	}

	/**
	 * @return the taskGroupId
	 */
	public String getTaskGroupId() {
		return taskGroupId;
	}

	/**
	 * @param taskGroupId the taskGroupId to set
	 */
	public void setTaskGroupId(String taskGroupId) {
		this.taskGroupId = taskGroupId;
	}

	/**
	 * @return the createUser
	 */
	public String getCreateUser() {
		return createUser;
	}

	/**
	 * @param createUser the createUser to set
	 */
	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}

	/**
	 * @return the myTaskGroupId
	 */
	public String getMyTaskGroupId() {
		return myTaskGroupId;
	}

	/**
	 * @param myTaskGroupId the myTaskGroupId to set
	 */
	public void setMyTaskGroupId(String myTaskGroupId) {
		this.myTaskGroupId = myTaskGroupId;
	}

	/**
	 * @return the deliver
	 */
	public String getDeliver() {
		return deliver;
	}

	/**
	 * @param deliver the deliver to set
	 */
	public void setDeliver(String deliver) {
		this.deliver = deliver;
	}

	/**
	 * @return the categoryId
	 */
	public String getCategoryId() {
		return categoryId;
	}

	/**
	 * @param categoryId the categoryId to set
	 */
	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public String toWorkOrderReport() {

		return "toWorkOrderReport";
	}

	private String reportType;

	/**
	 * @return the reportType
	 */
	public String getReportType() {
		return reportType;
	}

	/**
	 * @param reportType the reportType to set
	 */
	public void setReportType(String reportType) {
		this.reportType = reportType;
	}

	private Map<String, Object> valueMap;

	/**
	 * @return the valueMap
	 */
	public Map<String, Object> getValueMap() {
		return valueMap;
	}

	/**
	 * @param valueMap the valueMap to set
	 */
	public void setValueMap(Map<String, Object> valueMap) {
		this.valueMap = valueMap;
	}

	public String workOrderReport() {
		String appendHql = "";
		String appendSql = "";
		List<Object> vs = new ArrayList<Object>();
		if (responser != null && responser.length() > 0) {
			appendHql += " and wo.owner.username=?";
			appendSql += " and wo.owner_user_name=?";
			vs.add(responser);
		}

		if (commonQuestionType != null && commonQuestionType.length() > 0) {
			appendHql += " and wo.question.extraValue['commonQuestionType'].value=?";
			appendSql += " and wo.commonQuestionType=?";
			vs.add(commonQuestionType);
		} else if (class2 != null && class2.length() > 0) {
			appendHql += " and wo.question.extraValue['class2'].value=?";
			appendSql += " and wo.class2=?";
			vs.add(class2);
		} else if (class1 != null && class1.length() > 0) {
			appendHql += " and wo.question.extraValue['class1'].value=?";
			appendSql += " and wo.class1=?";
			vs.add(class1);
		}

		if (priority != null && priority.length() > 0) {
			appendHql += " and wo.priority=?";
			appendSql += " and wo.priority=?";
			vs.add(priority);
		}
		if (reportType.equals("detail")) {
			if (status != null && status.length() > 0) {
				appendHql += " and wo.status=?";
				appendSql += " and wo.status=?";
				vs.add(status);
			}
		}
		if (approveStatus != null && approveStatus.length() > 0) {
			appendHql += " and wo.approveStatus=?";
			appendSql += " and wo.approveStatus=?";
			vs.add(approveStatus);
		}
		if (questionType != null && questionType.length() > 0) {
			if (questionType.equals("CommonQuestion_product")) {
				appendHql += " and wo.question.type.name='CommonQuestionType' and wo.question.extraValue['isProductQAA'].value='true'";
				appendSql += " and wo.isProductQAA='true'";
			} else {
				appendHql += " and wo.question.type.name=?";
				appendSql += " and wo.typename=?";
				vs.add(questionType);
			}
		}
		if (responseGroup != null && responseGroup.length() > 0) {
			if (responseGroup.equals("C.01")) {
				appendHql += " and ( wo.responseGroup is null or wo.responseGroup=?)";
				appendSql += " and ( wo.responseGroup is null or wo.responseGroup=?)";
			} else {
				appendHql += " and wo.responseGroup=?";
				appendSql += " and wo.responseGroup=?";
			}
			vs.add(responseGroup);
		}

		if (taskGroupId != null && taskGroupId.length() > 0) {
			if (taskGroupId.equals("C.01")) {
				appendHql += " and ( wo.responseGroup is null or wo.responseGroup=?)";
				appendSql += " and ( wo.responseGroup is null or wo.responseGroup=?)";
			} else {
				appendHql += " and wo.responseGroup=?";
				appendSql += " and wo.responseGroup=?";
			}
			vs.add(taskGroupId);
		}
		Date currentDate = JspUtil.currentDate();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmm");
		if (startDate == null || startDate.length() == 0) {
			startDate = sdf.format(currentDate);
		}

		startDate += " 00:00";
		if (endDate == null || endDate.length() == 0) {
			endDate = sdf.format(currentDate);
		}

		endDate += " 23:59";
		Date startDateD = JspUtil.toDate(startDate, "yyyy-MM-dd HH:mm");
		Date endDateD = JspUtil.toDate(endDate, "yyyy-MM-dd HH:mm");
		List<Object> valueList = new ArrayList<Object>();
		if (reportType != null) {
			if (reportType.equals("summary")) {
				if (taskGroupId == null || taskGroupId.length() == 0) {
					Object[] taskGroupIds = baseMgr.customHqlQuery("select id from TaskGroup order by id asc", null);

					String hql = "from WorkOrder wo where wo.status=? and wo.createDate >=? and wo.createDate <? and wo.responseGroup=? "
							+ appendHql;

					valueMap = new TreeMap<String, Object>();
					for (Object obj : taskGroupIds) {

						String id = (String) obj;
						valueList = new ArrayList<Object>();
						valueList.add(Integer.valueOf(0));
						valueList.add(startDateD);
						valueList.add(endDateD);
						valueList.add(id);

						valueList.addAll(vs);

						long count0 = baseMgr.countByHql(hql, valueList.toArray());
						valueList.set(0, 2);
						long count2 = baseMgr.countByHql(hql, valueList.toArray());
						if (id.equals("C.01")) {
							// 加入responsegroup为null的数量
							String hqlNull = "from WorkOrder wo where wo.status=? and wo.responseGroup is null and wo.createDate>=? and wo.createDate<? "
									+ appendHql;
							valueList = new ArrayList<Object>();
							valueList.add(0);
							valueList.add(startDateD);
							valueList.add(endDateD);
							valueList.addAll(vs);
							long c0 = baseMgr.countByHql(hqlNull, valueList.toArray());
							valueList.set(0, 2);
							long c2 = baseMgr.countByHql(hqlNull, valueList.toArray());
							count0 += c0;
							count2 += c2;
						}
						Object[] values = new Object[2];
						values[0] = count0;
						values[1] = count2;
						valueMap.put(id, values);
					}

				} else {
					Object[] userIds = baseMgr.customHqlQuery(
							"select user.username from TaskGroupUser where taskGroup.id=? order by user.username asc",
							new Object[] { taskGroupId });
					String hql = "from WorkOrder wo where wo.status=? and wo.owner.username=? and wo.createDate>=? and wo.createDate<?"
							+ appendHql;
					valueMap = new TreeMap<String, Object>();
					for (Object obj : userIds) {
						String userId = (String) obj;
						valueList = new ArrayList<Object>();
						valueList.add(0);
						valueList.add(userId);
						valueList.add(startDateD);
						valueList.add(endDateD);
						valueList.addAll(vs);
						long count0 = baseMgr.countByHql(hql, valueList.toArray());
						valueList.set(0, 2);
						long count2 = baseMgr.countByHql(hql, valueList.toArray());
						Object[] values = new Object[2];
						values[0] = count0;
						values[1] = count2;
						valueMap.put(userId, values);
					}
				}
			} else if (reportType.equals("KPI")) {
				if (taskGroupId == null || taskGroupId.length() == 0) {
					Object[] taskGroupIds = baseMgr.customHqlQuery("select id from TaskGroup order by id asc", null);
					String sql = "select count(*) count_ from VIEW_WORKORDER_KPI wo where wo.STATUS=? and wo.RESPONSEGROUP =? and to_char(wo.CREATEDATE, 'yyyymmddHH24mi')>=? and to_char(wo.CREATEDATE, 'yyyymmddHH24mi')<? and wo.FINISHTIME is not null and wo.STARTTIME is not null and to_date(to_char(wo.FINISHTIME, 'yyyymmddHH24') , 'yyyymmddHH24')-to_date(to_char(wo.STARTTIME, 'yyyymmddHH24') , 'yyyymmddHH24')<? and to_date(to_char(wo.FINISHTIME, 'yyyymmddHH24') , 'yyyymmddHH24')-to_date(to_char(wo.STARTTIME, 'yyyymmddHH24') , 'yyyymmddHH24')>=?"
							+ appendSql;

					valueMap = new TreeMap<String, Object>();
					for (Object obj : taskGroupIds) {
						String id = (String) obj;
						valueList = new ArrayList<Object>();
						valueList.add(0);
						valueList.add(id);
						valueList.add(sdf2.format(startDateD));
						valueList.add(sdf2.format(endDateD));
						valueList.add(1);
						valueList.add(0);
						valueList.addAll(vs);
						Object[] c01 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 2);
						valueList.set(5, 1);
						Object[] c02 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 3);
						valueList.set(5, 2);
						Object[] c03 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 4);
						valueList.set(5, 3);
						Object[] c04 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 5);
						valueList.set(5, 4);
						Object[] c05 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 9999);
						valueList.set(5, 5);
						Object[] c06 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(0, 2);
						valueList.set(4, 1);
						valueList.set(5, 0);
						Object[] c21 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 2);
						valueList.set(5, 1);
						Object[] c22 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 3);
						valueList.set(5, 2);
						Object[] c23 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 4);
						valueList.set(5, 3);
						Object[] c24 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 5);
						valueList.set(5, 4);
						Object[] c25 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 9999);
						valueList.set(5, 5);
						Object[] c26 = baseMgr.queryBySql(sql, valueList.toArray());
						if (id.equals("C.01")) {
							String sqlNull = "select count(*) count_ from VIEW_WORKORDER_KPI wo where wo.STATUS=? and wo.RESPONSEGROUP =? and to_char(wo.CREATEDATE, 'yyyymmddHH24mi')>=? and to_char(wo.CREATEDATE, 'yyyymmddHH24mi')<? and wo.FINISHTIME is not null and wo.STARTTIME is not null and to_date(to_char(wo.FINISHTIME, 'yyyymmddHH24') , 'yyyymmddHH24')-to_date(to_char(wo.STARTTIME, 'yyyymmddHH24') , 'yyyymmddHH24')<? and to_date(to_char(wo.FINISHTIME, 'yyyymmddHH24') , 'yyyymmddHH24')-to_date(to_char(wo.STARTTIME, 'yyyymmddHH24') , 'yyyymmddHH24')>=?"
									+ appendSql;
							valueList = new ArrayList<Object>();
							valueList.add(0);
							valueList.add(id);
							valueList.add(sdf2.format(startDateD));
							valueList.add(sdf2.format(endDateD));
							valueList.add(1);
							valueList.add(0);
							valueList.addAll(vs);
							Object[] c_01 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 2);
							valueList.set(5, 1);
							Object[] c_02 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 3);
							valueList.set(5, 2);
							Object[] c_03 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 4);
							valueList.set(5, 3);
							Object[] c_04 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 5);
							valueList.set(5, 4);
							Object[] c_05 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 9999);
							valueList.set(5, 5);
							Object[] c_06 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(0, 2);
							valueList.set(4, 1);
							valueList.set(5, 0);
							Object[] c_21 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 2);
							valueList.set(5, 1);
							Object[] c_22 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 3);
							valueList.set(5, 2);
							Object[] c_23 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 4);
							valueList.set(5, 3);
							Object[] c_24 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 5);
							valueList.set(5, 4);
							Object[] c_25 = baseMgr.queryBySql(sqlNull, valueList.toArray());
							valueList.set(4, 9999);
							valueList.set(5, 5);
							Object[] c_26 = baseMgr.queryBySql(sqlNull, valueList.toArray());

							((Map) c01[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c01[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_01[0]).get("COUNT_"))))));
							((Map) c02[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c02[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_02[0]).get("COUNT_"))))));
							((Map) c03[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c03[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_03[0]).get("COUNT_"))))));
							((Map) c04[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c04[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_04[0]).get("COUNT_"))))));
							((Map) c05[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c05[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_05[0]).get("COUNT_"))))));
							((Map) c06[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c06[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_06[0]).get("COUNT_"))))));
							((Map) c21[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c21[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_21[0]).get("COUNT_"))))));
							((Map) c22[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c22[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_22[0]).get("COUNT_"))))));
							((Map) c23[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c23[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_23[0]).get("COUNT_"))))));
							((Map) c24[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c24[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_24[0]).get("COUNT_"))))));
							((Map) c25[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c25[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_25[0]).get("COUNT_"))))));
							((Map) c26[0]).put("COUNT_", ((Long.valueOf((String) ((Map) c26[0]).get("COUNT_"))) + ((Long
									.valueOf((String) ((Map) c_26[0]).get("COUNT_"))))));
						}
						Object[] values = new Object[12];
						values[0] = c01[0];
						values[1] = c02[0];
						values[2] = c03[0];
						values[3] = c04[0];
						values[4] = c05[0];
						values[5] = c06[0];
						values[6] = c21[0];
						values[7] = c22[0];
						values[8] = c23[0];
						values[9] = c24[0];
						values[10] = c25[0];
						values[11] = c26[0];

						valueMap.put(id, values);
					}
				} else {
					Object[] userIds = baseMgr.customHqlQuery(
							"select user.username from TaskGroupUser where taskGroup.id=? order by user.username asc",
							new Object[] { taskGroupId });
					String sql = "select count(*) count_ from VIEW_WORKORDER_KPI wo where wo.STATUS=? and wo.OWNER_USER_NAME=? and to_char(wo.CREATEDATE, 'yyyymmddHH24mi')>=? and to_char(wo.CREATEDATE, 'yyyymmddHH24mi')<? and wo.FINISHTIME is not null and wo.STARTTIME is not null and to_date(to_char(wo.FINISHTIME, 'yyyymmddHH24') , 'yyyymmddHH24')-to_date(to_char(wo.STARTTIME, 'yyyymmddHH24') , 'yyyymmddHH24')<? and to_date(to_char(wo.FINISHTIME, 'yyyymmddHH24') , 'yyyymmddHH24')-to_date(to_char(wo.STARTTIME, 'yyyymmddHH24') , 'yyyymmddHH24')>=? "
							+ appendSql;

					valueMap = new TreeMap<String, Object>();
					for (Object obj : userIds) {
						String id = (String) obj;
						valueList = new ArrayList<Object>();
						valueList.add(0);
						valueList.add(id);
						valueList.add(sdf2.format(startDateD));
						valueList.add(sdf2.format(endDateD));
						valueList.add(1);
						valueList.add(0);
						valueList.addAll(vs);
						Object[] c01 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 2);
						valueList.set(5, 1);
						Object[] c02 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 3);
						valueList.set(5, 2);
						Object[] c03 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 4);
						valueList.set(5, 3);
						Object[] c04 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 5);
						valueList.set(5, 4);
						Object[] c05 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 9999);
						valueList.set(5, 5);
						Object[] c06 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(0, 2);
						valueList.set(4, 1);
						valueList.set(5, 0);
						Object[] c21 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 2);
						valueList.set(5, 1);
						Object[] c22 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 3);
						valueList.set(5, 2);
						Object[] c23 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 4);
						valueList.set(5, 3);
						Object[] c24 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 5);
						valueList.set(5, 4);
						Object[] c25 = baseMgr.queryBySql(sql, valueList.toArray());
						valueList.set(4, 9999);
						valueList.set(5, 5);
						Object[] c26 = baseMgr.queryBySql(sql, valueList.toArray());

						Object[] values = new Object[12];
						values[0] = c01[0];
						values[1] = c02[0];
						values[2] = c03[0];
						values[3] = c04[0];
						values[4] = c05[0];
						values[5] = c06[0];
						values[6] = c21[0];
						values[7] = c22[0];
						values[8] = c23[0];
						values[9] = c24[0];
						values[10] = c25[0];
						values[11] = c26[0];

						valueMap.put(id, values);
					}
				}
			} else if (reportType.equals("detail")) {
				String hql = "from WorkOrder wo where wo.createDate>=? and wo.createDate<?" + appendHql;
				valueList = new ArrayList<Object>();
				valueList.add(startDateD);
				valueList.add(endDateD);
				valueList.addAll(vs);
				tp = JspUtil.pageableTag("detail", 10, 10);
				workOrders = JspUtil.queryByHql(hql, valueList.toArray(), tp);
			}
		}
		return "workOrderReport";
	}

	private String responseGroup;

	/**
	 * @return the responseGroup
	 */
	public String getResponseGroup() {
		return responseGroup;
	}

	/**
	 * @param responseGroup the responseGroup to set
	 */
	public void setResponseGroup(String responseGroup) {
		this.responseGroup = responseGroup;
	}

	public String downloadWorkOrderDetail() {
		String hqlAll = "from WorkOrder where createDate >=? and createDate <?";
		String hqlGroup = "from WorkOrder where responseGroup=? and createDate>=? and createDate<?";
		String hqlGroupNull = "from WorkOrder where ( responseGroup=? or responseGroup is null) and createDate>=? and createDate<?";
		String hqlUser = "from WorkOrder where owner.username=? and createDate>=? and createDate<?";
		String appendHql = "";
		if (taskGroupId != null) {
			responseGroup = taskGroupId;
		}
		List<Object> vs = new ArrayList<Object>();
		if (status != null && status.length() > 0) {
			appendHql += " and status=?";
			vs.add(status);
		}
		if (priority != null && priority.length() > 0) {
			appendHql += " and priority=?";
			vs.add(priority);
		}
		if (commonQuestionType != null && commonQuestionType.length() > 0) {
			appendHql += " and question.extraValue['commonQuestionType'].value=?";
			vs.add(commonQuestionType);
		} else if (class2 != null && class2.length() > 0) {
			appendHql += " and question.extraValue['class2'].value=?";
			vs.add(class2);
		} else if (class1 != null && class1.length() > 0) {
			appendHql += " and question.extraValue['class1'].value=?";
			vs.add(class1);
		}
		if (approveStatus != null && approveStatus.length() > 0) {
			appendHql += " and approveStatus=?";
			vs.add(approveStatus);
		}
		if (questionType != null && questionType.length() > 0) {
			appendHql += " and question.type.name=?";
			vs.add(questionType);
		}
		if ("summary".equals(reportType)) {
			appendHql += " and (status=? or status=?)";
			vs.add(2);
			vs.add(0);
		}
		Date currentDate = JspUtil.currentDate();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (startDate == null || startDate.length() == 0) {
			startDate = sdf.format(currentDate);
		}
		startDate += " 00:00";
		if (endDate == null || endDate.length() == 0) {
			endDate = sdf.format(currentDate);
		}
		endDate += " 23:59";
		Date startDateD = JspUtil.toDate(startDate, "yyyy-MM-dd HH:mm");
		Date endDateD = JspUtil.toDate(endDate, "yyyy-MM-dd HH:mm");
		Object[] wos = null;
		List<Object> valueList = new ArrayList<Object>();
		if ((responseGroup == null || responseGroup.length() == 0) && (responser == null || responser.length() == 0)) {
			wos = baseMgr.queryByHql(hqlAll, new Object[] { startDateD, endDateD });
		} else if (responseGroup != null && responseGroup.length() > 0 && responser != null && responser.length() > 0) {

			valueList.add(responser);
			valueList.add(startDateD);
			valueList.add(endDateD);
			valueList.addAll(vs);
			if (responseGroup.equals("C.01")) {
				appendHql += " and (responseGroup is null or responseGroup=?)";
			} else {
				appendHql += " and responseGroup=?";
			}
			valueList.add(responseGroup);

			wos = baseMgr.queryByHql(hqlUser + appendHql, valueList.toArray());

		} else if (responseGroup != null && responseGroup.length() > 0) {
			valueList.add(responseGroup);
			valueList.add(startDateD);
			valueList.add(endDateD);
			valueList.addAll(vs);
			if (responseGroup.equals("C.01")) {
				wos = baseMgr.queryByHql(hqlGroupNull + appendHql, valueList.toArray());
			} else {
				wos = baseMgr.queryByHql(hqlGroup + appendHql, valueList.toArray());
			}
		}
		content = buildCsv(wos);
		file = "workOrderList.csv";
		return "downloadWorkOrderDetail";
	}

	private Map<String, Object> valueMapHeader;

	/**
	 * @return the valueMapHeader
	 */
	public Map<String, Object> getValueMapHeader() {
		return valueMapHeader;
	}

	/**
	 * @param valueMapHeader the valueMapHeader to set
	 */
	public void setValueMapHeader(Map<String, Object> valueMapHeader) {
		this.valueMapHeader = valueMapHeader;
	}

	public String console() {
		Date currentDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmm");
		String date = sdf.format(currentDate);
		date += "0000";
		Date dateS = null;
		Boolean isCSR = false;
		// User theUser = AdminHelper.getUser();
		if (taskGroupId != null && taskGroupId.length() > 0) {
			if (taskGroupId.startsWith("C")) {
				isCSR = true;
			}
		}
		// Object[] taskGroups = baseMgr.queryByHql("from TaskGroupUser where user.username=?", new Object[] { theUser
		// .getUsername() });
		// for (int i = 0; i < taskGroups.length; i++) {
		// TaskGroupUser tga = (TaskGroupUser) taskGroups[i];
		// if (tga.getTaskGroup().getId().substring(0, 1).equals("C")) {
		// isCSR = true;
		// }
		// }
		try {
			dateS = sdf2.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Object[] users = baseMgr.queryByHql("from TaskGroupUser where taskGroup.id=? order by user.username asc",
				new Object[] { taskGroupId });
		String todayFinishHql = "from WorkOrder where status=? and finishTime>=?";
		String notFinishHql = "from WorkOrder where status!=?";
		String statusHql = "from WorkOrder where status=?";
		String notGetHql = " from WorkOrder where status=? and owner.username is null";
		String needApproveHql = "from WorkOrder where approveStatus=?";
		String groupHql = "";
		if (isCSR) {

			groupHql = " and (responseGroup=? or responseGroup is null)";
		} else {
			groupHql = " and responseGroup=?";
		}
		Long countGroupTodayFinish = baseMgr.countByHql(todayFinishHql + groupHql, new Object[] { 2, dateS, taskGroupId });
		Long countGroupNotGet = baseMgr.countByHql(notGetHql + groupHql, new Object[] { 0, taskGroupId });
		Long countGroupNeedApprove = baseMgr.countByHql(needApproveHql + groupHql, new Object[] { 0, taskGroupId });
		Long countGroupNotFinish = baseMgr.countByHql(notFinishHql + groupHql, new Object[] { 2, taskGroupId });
		Long countGroupForward = baseMgr.countByHql(statusHql + groupHql, new Object[] { 3, taskGroupId });
		Long countGroupInit = baseMgr.countByHql(statusHql + groupHql, new Object[] { 0, taskGroupId });
		Long countGroupReturn = baseMgr.countByHql(statusHql + groupHql, new Object[] { 4, taskGroupId });
		List<Object> headValueList = new ArrayList<Object>();
		headValueList.add(countGroupTodayFinish);
		headValueList.add(countGroupNotGet);
		headValueList.add(countGroupNeedApprove);
		headValueList.add(countGroupNotFinish);
		headValueList.add(countGroupForward);
		headValueList.add(countGroupInit);
		headValueList.add(countGroupReturn);
		valueMapHeader = new HashMap<String, Object>();
		valueMapHeader.put(taskGroupId, headValueList);
		if (taskGroupId.substring(0, 1).equals("C")) {
			String C02GroupHql = " and responseGroup=?";
			countGroupTodayFinish = baseMgr.countByHql(todayFinishHql + C02GroupHql, new Object[] { 2, dateS, "C.02" });
			countGroupNotGet = baseMgr.countByHql(notGetHql + C02GroupHql, new Object[] { 0, "C.02" });
			countGroupNeedApprove = baseMgr.countByHql(needApproveHql + C02GroupHql, new Object[] { 0, "C.02" });
			countGroupNotFinish = baseMgr.countByHql(notFinishHql + C02GroupHql, new Object[] { 2, "C.02" });
			countGroupForward = baseMgr.countByHql(statusHql + C02GroupHql, new Object[] { 3, "C.02" });
			countGroupInit = baseMgr.countByHql(statusHql + C02GroupHql, new Object[] { 0, "C.02" });
			countGroupReturn = baseMgr.countByHql(statusHql + C02GroupHql, new Object[] { 4, "C.02" });
			headValueList = new ArrayList<Object>();
			headValueList.add(countGroupTodayFinish);
			headValueList.add(countGroupNotGet);
			headValueList.add(countGroupNeedApprove);
			headValueList.add(countGroupNotFinish);
			headValueList.add(countGroupForward);
			headValueList.add(countGroupInit);
			headValueList.add(countGroupReturn);
			valueMapHeader.put("C.02", headValueList);
		}

		valueMap = new TreeMap<String, Object>();
		String userHql = "";
		if (!isCSR) {
			userHql = " and owner.username=? and responseGroup=?";
		} else {
			userHql = " and owner.username=? and (responseGroup=? or responseGroup is null)";
		}
		for (Object obj : users) {
			TaskGroupUser user = (TaskGroupUser) obj;
			List<Object> valueList = new ArrayList<Object>();
			Long countTodayFinish = baseMgr.countByHql(todayFinishHql + userHql, new Object[] { 2, dateS,
					user.getUser().getUsername(), taskGroupId });
			Long countNotFinish = baseMgr.countByHql(notFinishHql + userHql, new Object[] { 2, user.getUser().getUsername(),
					taskGroupId });
			Long countForward = baseMgr.countByHql(statusHql + userHql, new Object[] { 3, user.getUser().getUsername(),
					taskGroupId });
			Long countInit = baseMgr.countByHql(statusHql + userHql, new Object[] { 0, user.getUser().getUsername(),
					taskGroupId });
			Long countReturn = baseMgr.countByHql(statusHql + userHql, new Object[] { 4, user.getUser().getUsername(),
					taskGroupId });
			valueList.add(countTodayFinish);
			valueList.add(countNotFinish);
			valueList.add(countForward);
			valueList.add(countInit);
			valueList.add(countReturn);
			valueMap.put(user.getUser().getUsername(), valueList);
		}

		return "console";
	}

	public String toApprove() {
		WorkOrder wo = (WorkOrder) baseMgr.get(WorkOrder.class, Long.valueOf(id));
		if (wo.getApprover() != null) {
			message = "本工单已有人审核";
			return "result";
		} else {
			wo.setApprover(AdminHelper.getUser().getUsername());
			WorkOrderApprove woa = new WorkOrderApprove();
			woa.setWorkOrderId(wo.getId());
			woa.setStartDate(new Date());
			woa.setApprover(wo.getApprover());
			woa.setApproveStatus("0");
			baseMgr.save(woa);
			wo.setApproveId(woa.getId());
		}
		baseMgr.update(wo);
		return "toApprove";
	}

	public String returnShipfareException() {
		Question question = (Question) baseMgr.get(Question.class, id);
		String orderId = question.getExtraValue().get("orderId").getValue();
		String shipfareStr = question.getExtraValue().get("shipfare").getValue();

		Float shipfare = Float.valueOf(shipfareStr);
		serviceOrderService.returnShipfareException(orderId, shipfare);
		workOrderService.closeOrder(id, null, "false", workOrderId, note, WorkOrder.FINISH_TYPE.SELF.value(), null, null,
				null, null);
		message = "已生成退款申请，运费：" + shipfareStr + "";
		return "returnShipfareException";
	}

	private Object[] questionTypes;
	private QuestionType theQuestionType;

	/**
	 * @return the questionTypes
	 */
	public Object[] getQuestionTypes() {
		return questionTypes;
	}

	/**
	 * @param questionTypes the questionTypes to set
	 */
	public void setQuestionTypes(Object[] questionTypes) {
		this.questionTypes = questionTypes;
	}

	/**
	 * @return the theQuestionType
	 */
	public QuestionType getTheQuestionType() {
		return theQuestionType;
	}

	/**
	 * @param theQuestionType the theQuestionType to set
	 */
	public void setTheQuestionType(QuestionType theQuestionType) {
		this.theQuestionType = theQuestionType;
	}

	public String listWorkOrderType() {
		questionTypes = baseMgr.queryByHql("from QuestionType order by name asc", null);

		return "listWorkOrderType";
	}

	public String getWorkOrderType() {
		questionTypes = baseMgr.queryByHql("from QuestionType order by name asc", null);
		if (questionTypes != null) {
			for (Object obj : questionTypes) {
				QuestionType qt = (QuestionType) obj;
				if (qt.getName().equals(questionType)) {
					theQuestionType = qt;
					break;
				}
			}
		}
		return "listWorkOrderType";
	}

	private String name;
	private String description;
	private String needWorkOrder;
	private String workFlowName;
	private String needAnswer;
	private String formName;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the description
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * @param description the description to set
	 */
	public void setDescription(String description) {
		this.description = description;
	}

	/**
	 * @return the needWorkOrder
	 */
	public String getNeedWorkOrder() {
		return needWorkOrder;
	}

	/**
	 * @param needWorkOrder the needWorkOrder to set
	 */
	public void setNeedWorkOrder(String needWorkOrder) {
		this.needWorkOrder = needWorkOrder;
	}

	/**
	 * @return the workFlowName
	 */
	public String getWorkFlowName() {
		return workFlowName;
	}

	/**
	 * @param workFlowName the workFlowName to set
	 */
	public void setWorkFlowName(String workFlowName) {
		this.workFlowName = workFlowName;
	}

	/**
	 * @return the needAnswer
	 */
	public String getNeedAnswer() {
		return needAnswer;
	}

	/**
	 * @param needAnswer the needAnswer to set
	 */
	public void setNeedAnswer(String needAnswer) {
		this.needAnswer = needAnswer;
	}

	/**
	 * @return the formName
	 */
	public String getFormName() {
		return formName;
	}

	/**
	 * @param formName the formName to set
	 */
	public void setFormName(String formName) {
		this.formName = formName;
	}

	public String updateWorkOrderType() {
		QuestionType qt = (QuestionType) baseMgr.get(QuestionType.class, name);
		boolean isExist = true;
		if (qt == null) {
			isExist = false;
			qt = new QuestionType();
		}
		qt.setDescription(description);
		Form form = null;
		if (formName != null) {
			form = (Form) baseMgr.get(Form.class, formName);
		}
		qt.setExtraAttr(form);
		qt.setName(name);
		if (needAnswer != null) {
			qt.setNeedAnswer(Boolean.valueOf(needAnswer));
		}
		if (needWorkOrder != null) {
			qt.setNeedWorkOrder(Boolean.valueOf(needWorkOrder));
		}
		qt.setWorkFlowName(workFlowName);
		if (isExist) {
			baseMgr.update(qt);
		} else {
			baseMgr.save(qt);
		}
		theQuestionType = qt;
		listWorkOrderType();
		message = "工单类型已更新资料";
		return "updateWorkOrderType";
	}

	public String getCompensation() {
		return compensation;
	}

	public void setCompensation(String compensation) {
		this.compensation = compensation;
	}

	public SmsService getSmsService() {
		return smsService;
	}

	public void setSmsService(SmsService smsService) {
		this.smsService = smsService;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
